package com.huxiu.pagers.qunzu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.APP;
import com.huxiu.R;
import com.huxiu.base.ZiXunDetailPager;
import com.huxiu.holder.QunZuHolder;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.QunZuList;
import com.huxiu.net.responses.QunZuListDataResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.Global;
import com.huxiu.utils.NetUtil;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by ${qcl} on 2015/11/19.
 */
public class QunZuDetailMine extends ZiXunDetailPager {
    @ViewInject(R.id.lv_tabdetail_list)
    private ListView lv_tabdetail_list;

    @ViewInject(R.id.loading)
    private LinearLayout loading;// 加载中
    @ViewInject(R.id.reLoadView)
    private LinearLayout reLoadView;// 重新加载
    private Runnable runnable;
    private Handler handler;

    public QunZuDetailMine(Context context) {
        super(context);
    }

    @Override
    protected View initView() {
        View viewAll = View.inflate(mContext, R.layout.list_no_refresh, null);
        ViewUtils.inject(this, viewAll);
        //在oncreat等中实例化
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                //要做的事情
                reLoadView.setVisibility(View.VISIBLE);
                loading.setVisibility(View.INVISIBLE);
            }
        };
        // 给下拉刷新Listview设置监听器
        return viewAll;
    }

    @OnClick({R.id.reLoadView})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.reLoadView:
                reLoadView.setVisibility(View.GONE);
                loading.setVisibility(View.VISIBLE);
                lv_tabdetail_list.setVisibility(View.VISIBLE);
                initData();
                break;
        }
    }

    @Override
    public void initData() {
        if (!NetUtil.checkNet(mContext)) {
            Utils.showToast(R.string.generic_check);
            reLoadView.setVisibility(View.VISIBLE);
            loading.setVisibility(View.INVISIBLE);
            lv_tabdetail_list.setVisibility(View.GONE);
            return;
        } else {
            reLoadView.setVisibility(View.GONE);
            loading.setVisibility(View.VISIBLE);
            lv_tabdetail_list.setVisibility(View.VISIBLE);
        }
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                loadList();
                handler.postDelayed(runnable, Constants.TIME_RELOADE);
            }
        });
        IntentFilter intent = new IntentFilter();
        intent.addAction(Constants.INTENT_QUNZU_JOIN_CHANGE);
        LocalBroadcastManager.getInstance(APP.getInstance()).registerReceiver(mReceiver, intent);
    }

    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            loadList();
        }
    };

    private List<QunZuList.ForumJoined> lists = new ArrayList<>();
    private List<QunZuList.ForumJoined> lists2 = new ArrayList<>();
    private String noListKey;

    private void loadList() {
        String url = NetworkConstants.MY_FORUM_ALL_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.uid);
        //        params.put("uid", "290388");
        GsonRequest<QunZuListDataResponse> request = new GsonRequest<>(url, Request.Method.POST,
                QunZuListDataResponse.class, false, params,
                new Response.Listener<QunZuListDataResponse>() {
                    @Override
                    public void onResponse(QunZuListDataResponse response) {
                        if (response.isSuccess()) {
                            handler.removeCallbacks(runnable);
                            loading.setVisibility(View.INVISIBLE);
                            reLoadView.setVisibility(View.GONE);
                            if (response.data.forum_joined_total == 0 && response.data.forum_create_total == 0) {
                                noListKey = "nolist";
                                adapter = new SpareAdapter();
                                lv_tabdetail_list.setAdapter(adapter);
                            } else {
                                if (lists != null && lists.size() > 0) {
                                    lists.clear();
                                }
                                if (lists2 != null && lists2.size() > 0) {
                                    lists2.clear();
                                }
                                Collections.addAll(lists, response.data.forum_joined);
                                Collections.addAll(lists2, response.data.forum_create);
                                noListKey = "";
                                adapter = new SpareAdapter();
                                lv_tabdetail_list.setAdapter(adapter);
                            }
                        } else {
                            Utils.showToast(response.error.message);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //                Utils.showToast(R.string.generic_failure);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    SpareAdapter adapter;

    private class SpareAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            if (!TextUtils.isEmpty(noListKey)) {
                return 1;
            } else {
                return (lists.size() + lists2.size());
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            QunZuHolder holder;
            View view = convertView;
            if (view == null) {
                view = View.inflate(mContext, R.layout.item_mine_qunzu_list, null);
                holder = new QunZuHolder(view, mContext);
                view.setTag(holder);
            }
            holder = (QunZuHolder) view.getTag();
            if (!TextUtils.isEmpty(noListKey)) {
                holder.setAdapter(adapter);
                holder.bindItem(noListKey, position);
            } else {
                QunZuList.ForumJoined item;
                if (position < lists.size()) {
                    item = lists.get(position);
                } else if (position < lists.size() + lists2.size()) {
                    item = lists2.get(position - lists.size());
                } else {
                    item = lists2.get(lists2.size() - 1);
                }
                holder.setAdapter(adapter);
                holder.bindItem(item, position, lists.size(), Constants.GROUP_OF_MYGROUP);//这里用来把获取到的数据传递给holder
            }
            return view;
        }
    }
}
